package com.example.demo.demos.web.service;

import com.example.demo.demos.web.dto.TextToSpeechDTO;
import com.example.demo.demos.web.properties.TtsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


@Service
@Slf4j
public class TextToSpeechServiceImpl implements TextToSpeechService {

    private final TtsProperties ttsProperties;
    private final CloseableHttpClient httpClient;

    public TextToSpeechServiceImpl(TtsProperties ttsProperties) {
        this.ttsProperties = ttsProperties;
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        // 最大连接数-不设默认20
        connectionManager.setMaxTotal(200);
        // 每个路由最大连接数-不设默认2
//        connectionManager.setDefaultMaxPerRoute(100);
        this.httpClient = HttpClients.custom()
//                .setDefaultRequestConfig(
//                        RequestConfig.custom()
//                                .setConnectTimeout(5000)
//                                .setSocketTimeout(5000)
//                                .setConnectionRequestTimeout(5000)
//                                .build()
//                )
                .setConnectionManager(connectionManager)
                .build();
    }

    @Override
    public byte[] convertTextToSpeechStream(TextToSpeechDTO textToSpeechDTO) throws Exception {
        /**
         * voiceCode
         * speakText
         * speakSpeed
         * speakVolume
         * params
         */
        String encodedText = URLEncoder.encode(textToSpeechDTO.getText(), String.valueOf(StandardCharsets.UTF_8));
        String fileUrl = String.format("%s/forward?text=%s&speed=%d&volume=%d&pitch=%d",
                ttsProperties.getIp(),
                encodedText,
                ttsProperties.getSpeed(),
                ttsProperties.getVolume(),
                ttsProperties.getPitch());
        log.info(fileUrl);
        HttpGet httpGet = new HttpGet(fileUrl);
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toByteArray(response.getEntity());
        } else {
            throw new Exception("转换失败, 状态" + response.getStatusLine().getStatusCode());
        }
    }
}
